#!/user/bin/env python3
# -*- coding: utf-8 -*-
"""
--------------------------------------
    Author:     JiChao_Song
    Date  :     2022/1/19 15:06
    Desc  :
--------------------------------------
"""
import io
from urllib import parse

from django.core.paginator import Paginator
from django.db import transaction
from django.http import HttpResponse, StreamingHttpResponse, FileResponse
from django_http_log.common.request import BaseAPIView
from django_http_log.common.response import SuccessResponse, SystemExceptionResponse, CommonResponse, \
    ParamsErrorResponse

from common.decorator.token_decorator import Authentication
from common.enums.case_enums import CaseTypeEnum, CaseStepsTypeEnum, CaseImportanceEnum, CaseStatusEnum, \
    CaseImportTypeEnum
from common.enums.response_enums import CommonResultEnums, PioneerBaseExceptionResponse
from common.exception.base import PioneerBaseExceptions
from common.tools.ExcelExportClient import ExcelClient
from common.utils.log_utils import logger
from common.utils.other_utils import get_time, get_enum_str_list, queryDict
from common.utils.token_utils import RequestAuthTokenUtil
from common.utils.tool_utils import read_case_import_file, check_case_import_file
from extends.microseer.base.upload import upload_file
from person.models import CaseBase, Project, CaseImportRecord, CaseModule
from person.serializers.case import CaseBaseSerializer
from platform_auth.settings import APIDOC_DECORATOR, BASE_DIR


class CaseBaseAPIView(BaseAPIView):
    Model = CaseBase
    serializer_class = CaseBaseSerializer


class CaseBaseAddAPIView(CaseBaseAPIView):
    """用例模块添加"""

    @APIDOC_DECORATOR.checkParams
    @APIDOC_DECORATOR.start
    @APIDOC_DECORATOR.ApiTag(value = 'case', desc = '测试用例管理')
    @APIDOC_DECORATOR.ApiOperation(method = 'POST', path = '/case/Base/add', summary = '用例新增')
    @APIDOC_DECORATOR.ApiParams(value = 'caseVindicatorName', type = 'string', desc = '责任人名称')
    @APIDOC_DECORATOR.ApiParams(value = 'caseVindicatorId', type = 'int', desc = '责任人Id')
    @APIDOC_DECORATOR.ApiParams(value = 'caseImportance', type = 'int', desc = '优先级',
                                remark = get_enum_str_list(enumObj = CaseImportanceEnum))
    @APIDOC_DECORATOR.ApiParams(value = 'caseModuleId', type = 'int', desc = '用例所属模块')
    @APIDOC_DECORATOR.ApiParams(value = 'casePreCondition', type = 'string', desc = '前置条件')
    @APIDOC_DECORATOR.ApiParams(value = 'caseSteps', type = 'string', desc = '用例步骤')
    @APIDOC_DECORATOR.ApiParams(value = 'caseStepsType', type = 'int', desc = '用例步骤类型',
                                remark = get_enum_str_list(enumObj = CaseStepsTypeEnum))
    @APIDOC_DECORATOR.ApiParams(value = 'caseStatus', type = 'int', desc = '用例状态',
                                remark = get_enum_str_list(enumObj = CaseStatusEnum))
    @APIDOC_DECORATOR.ApiParams(value = 'caseDesc', type = 'string', desc = '用例描述')
    @APIDOC_DECORATOR.ApiParams(value = 'caseTitle', type = 'string', require = True, desc = '用例标题')
    @Authentication(isProject = True)
    def post(self, request, *args, **kwargs):
        try:
            body: dict = request.data.copy()

            userId, userName = RequestAuthTokenUtil(
                request = request).get_user_id_and_username()
            projectId = RequestAuthTokenUtil(request = request).get_project()
            # 1. 根据ProjectId判断项目是否存在
            queryset_project = Project.objects.filter(id = projectId, deleted = False)
            if queryset_project.count() == 0:
                return CommonResponse(codeEnums = CommonResultEnums.PROJECT_ID_IS_NOT_EXIST)

            # 2. 保存新增
            with transaction.atomic():
                caseBase = self.Model.objects.create(
                    creatorName = userName,
                    creatorId = userId,
                    caseTitle = body.get('caseTitle'),
                    caseDesc = body.get('caseDesc'),
                    caseStatus = body.get('caseStatus'),
                    caseStepsType = body.get('caseStepsType'),
                    caseSteps = body.get('caseSteps'),
                    casePreCondition = body.get('casePreCondition'),
                    caseModuleId = body.get('caseModuleId'),
                    caseImportance = body.get('caseImportance'),
                    caseVindicatorId = body.get('caseVindicatorId'),
                    caseVindicatorName = body.get('caseVindicatorName'),
                )
            # 3. 序列化
            serializer = self.serializer_class(
                caseBase, exclude = self.exclude_fields)

            return SuccessResponse(result = serializer.data)

        except Exception as e:

            logger.error(e)

            return SystemExceptionResponse()


class CaseBaseListAPIView(CaseBaseAPIView):
    """用例模块列表"""
    @APIDOC_DECORATOR.checkParams
    @APIDOC_DECORATOR.start
    @APIDOC_DECORATOR.ApiTag(value = 'case', desc = '测试用例管理')
    @APIDOC_DECORATOR.ApiOperation(method = 'POST', path = '/case/base/list', summary = '用例列表')
    @APIDOC_DECORATOR.ApiParams(value = 'runEndTime', type = 'int', desc = '执行结束时间')
    @APIDOC_DECORATOR.ApiParams(value = 'runStartTime', type = 'int', desc = '执行开始时间')
    @APIDOC_DECORATOR.ApiParams(value = 'createEndTime', type = 'int', desc = '创建结束时间')
    @APIDOC_DECORATOR.ApiParams(value = 'createStartTime', type = 'int', desc = '创建开始时间')
    @APIDOC_DECORATOR.ApiParams(value = 'creatorId', type = 'int', desc = '创建人')
    @APIDOC_DECORATOR.ApiParams(value = 'caseRunnerId', type = 'int', desc = '执行人Id')
    @APIDOC_DECORATOR.ApiParams(value = 'caseVindicatorId', type = 'int', desc = '责任人Id')
    @APIDOC_DECORATOR.ApiParams(value = 'caseImportance', type = 'int', desc = '优先级',
                                remark = get_enum_str_list(enumObj = CaseImportanceEnum))
    @APIDOC_DECORATOR.ApiParams(value = 'caseStatus', type = 'int', desc = '用例状态',
                                remark = get_enum_str_list(enumObj = CaseStatusEnum))
    @APIDOC_DECORATOR.ApiParams(value = 'caseTitle', type = 'string', require = False, desc = '用例标题')
    @APIDOC_DECORATOR.ApiParams(value = 'caseModuleId', type = 'int', require = False, desc = '用例模块id')
    @APIDOC_DECORATOR.ApiParams(value = 'pageSize', type = 'int', require = True, desc = '每页数量')
    @APIDOC_DECORATOR.ApiParams(value = 'pageIndex', type = 'int', require = True, desc = '页码')
    @Authentication(isProject = True)
    def post(self, request, *args, **kwargs):
        try:
            body: dict = request.data.copy()

            pageIndex = body.get('pageIndex')
            pageSize = body.get('pageSize')
            caseTitle = body.get('caseTitle')
            caseModuleId = body.get('caseModuleId')
            caseStatus = body.get('caseStatus')
            caseImportance = body.get('caseImportance')
            caseVindicatorId = body.get('caseVindicatorId')
            caseRunnerId = body.get('caseRunnerId')
            creatorId = body.get('creatorId')
            createStartTime = body.get('createStartTime')
            createEndTime = body.get('createEndTime')
            runStartTime = body.get('runStartTime')
            runEndTime = body.get('runEndTime')

            projectId = RequestAuthTokenUtil(request = request).get_project()

            queryset_sql_str = f"self.Model.objects.filter(deleted = False, project = {projectId}, "
            # 1. 用例标题
            if caseTitle and caseTitle != '':
                queryset_sql_str += f"caseTitle__icontains = {str(caseTitle).strip()}, "
            # 2. 用例模块
            if caseModuleId:
                if not isinstance(caseModuleId, int):
                    return ParamsErrorResponse(message = f'caseModuleId参数类型错误,期望int,实际{type(caseModuleId)}')
                if caseModuleId != 0:
                    queryset_sql_str += f"caseModuleId = {caseModuleId}, "
            # 3. 用例状态
            if caseStatus:
                if not isinstance(caseStatus, int):
                    return ParamsErrorResponse(message = f'caseStatu参数类型错误,期望int,实际{type(caseStatus)}')
                else:
                    queryset_sql_str += f"caseStatus = {caseStatus}, "
            # 4. 优先级
            if caseImportance:
                if not isinstance(caseImportance, int):
                    return ParamsErrorResponse(message = f'caseImportance参数类型错误,期望int,实际{type(caseImportance)}')
                else:
                    queryset_sql_str += f"caseImportance = {caseImportance}, "
            # 5. 责任人
            if caseVindicatorId:
                if not isinstance(caseVindicatorId, int):
                    return ParamsErrorResponse(message = f'caseVindicatorId参数类型错误,期望int,实际{type(caseVindicatorId)}')
                else:
                    queryset_sql_str += f"caseVindicatorId = {caseVindicatorId}, "
            # 6. 执行人
            if caseRunnerId:
                if not isinstance(caseRunnerId, int):
                    return ParamsErrorResponse(message = f'caseRunnerId参数类型错误,期望int,实际{type(caseRunnerId)}')
                else:
                    queryset_sql_str += f"caseRunnerId = {caseRunnerId}, "
            # 7. 创建人
            if creatorId:
                if isinstance(creatorId, int):
                    return ParamsErrorResponse(message = f'creatorId参数类型错误,期望int,实际{type(creatorId)}')
                else:
                    queryset_sql_str += f"creatorId = {creatorId}, "

            # 8. 创建时间
            if createStartTime and createStartTime != '':
                queryset_sql_str += f"createTime__gte = {createStartTime}, createTime__lte = {get_time() if createEndTime is None and createEndTime == '' else createEndTime}, "

            # 9. 执行时间
            if createStartTime and createStartTime != '':
                queryset_sql_str += f"caseRunTime__gte = {runStartTime}, caseRunTime__lte = {get_time() if runEndTime is None and runEndTime == '' else runEndTime}, "

            queryset_sql_str += ").order_by('-createTime').order_by('caseTitle')"

            logger.info(f'测试用例查询queryset: {queryset_sql_str}')

            queryset = eval(queryset_sql_str)
            serializer = self.serializer_class(queryset, many = True, exclude = self.exclude_fields)
            pageData = Paginator(serializer.data, pageSize)
            data = {
                'pageCount': pageData.count,
                'pageIndex': pageIndex,
                'pageSize': pageSize,
                'list': pageData.page(pageIndex).object_list
            }
            return SuccessResponse(result = data)

        except Exception as e:

            logger.error(e)

            return SystemExceptionResponse()


class CaseBaseEditAPIView(CaseBaseAPIView):
    """用例模块编辑"""

    @APIDOC_DECORATOR.checkParams
    @APIDOC_DECORATOR.start
    @APIDOC_DECORATOR.ApiTag(value = 'case', desc = '测试用例管理')
    @APIDOC_DECORATOR.ApiOperation(method = 'POST', path = '/case/Base/edit', summary = '用例编辑')
    @APIDOC_DECORATOR.ApiParams(value = 'caseRunTime', type = 'int', desc = '执行时间')
    @APIDOC_DECORATOR.ApiParams(value = 'caseRunnerName', type = 'string', desc = '执行人名称')
    @APIDOC_DECORATOR.ApiParams(value = 'caseRunnerId', type = 'int', desc = '执行人Id')
    @APIDOC_DECORATOR.ApiParams(value = 'caseVindicatorName', type = 'string', desc = '责任人名称')
    @APIDOC_DECORATOR.ApiParams(value = 'caseVindicatorId', type = 'int', desc = '责任人Id')
    @APIDOC_DECORATOR.ApiParams(value = 'caseImportance', type = 'int', desc = '优先级',
                                remark = get_enum_str_list(enumObj = CaseImportanceEnum))
    @APIDOC_DECORATOR.ApiParams(value = 'casePreCondition', type = 'string', desc = '前置条件')
    @APIDOC_DECORATOR.ApiParams(value = 'caseSteps', type = 'string', desc = '模块名称')
    # @APIDOC_DECORATOR.ApiParams(value = 'caseStepsType', type = 'string', desc = '用例步骤类型',
    #                             remark = get_enum_str_list(enumObj = CaseStepsTypeEnum))
    @APIDOC_DECORATOR.ApiParams(value = 'caseStatus', type = 'int', desc = '用例状态',
                                remark = get_enum_str_list(enumObj = CaseStatusEnum))
    @APIDOC_DECORATOR.ApiParams(value = 'caseDesc', type = 'string', desc = '用例描述')
    @APIDOC_DECORATOR.ApiParams(value = 'caseModuleId', type = 'int', require = True, desc = '用例所属模块')
    @APIDOC_DECORATOR.ApiParams(value = 'caseTitle', type = 'string', require = True, desc = '用例标题')
    @APIDOC_DECORATOR.ApiParams(value = 'caseId', type = 'int', require = True, desc = '用例标题')
    @Authentication(isProject = True)
    def post(self, request, *args, **kwargs):
        try:
            body: dict = request.data.copy()

            userId, userName = RequestAuthTokenUtil(
                request = request).get_user_id_and_username()
            projectId = RequestAuthTokenUtil(request = request).get_project()

            # 1. 根据ProjectId判断项目是否存在
            queryset_project = Project.objects.filter(id = projectId, deleted = False)
            if queryset_project.count() == 0:
                return CommonResponse(codeEnums = CommonResultEnums.PROJECT_ID_IS_NOT_EXIST)
            # 2. 根据caseId判断用例是否存在
            queryset_id = self.Model.objects.filter(
                id = body.get('caseId'), deleted = False)
            if queryset_id.count() == 0:
                return CommonResponse(codeEnums = CommonResultEnums.CASE_BASE_ID_IS_NOT_EXIST)
            # 3. 根据caseModuleId判断模块是否存在
            queryset_id = CaseModule.objects.filter(
                id = body.get('caseModuleId'), deleted = False, project = projectId)
            if queryset_id.count() == 0:
                return CommonResponse(codeEnums = CommonResultEnums.CASE_MODULE_ID_IS_NOT_EXIST)
            # 4. 更新
            with transaction.atomic():
                queryset_id.update(
                    updaterId = userId,
                    updaterName = userName,
                    updateTime = get_time(),
                    caseTitle = body.get('caseTitle'),
                    caseDesc = body.get('caseDesc'),
                    caseStatus = body.get('caseStatus'),
                    caseSteps = body.get('caseSteps'),
                    casePreCondition = body.get('casePreCondition'),
                    caseModuleId = body.get('caseModuleId'),
                    caseImportance = body.get('caseImportance'),
                    caseVindicatorId = body.get('caseVindicatorId'),
                    caseVindicatorName = body.get('caseVindicatorName'),
                    caseRunnerId = body.get('caseRunnerId'),
                    caseRunnerName = body.get('caseRunnerName'),
                    caseRunTime = body.get('caseRunTime'),
                )

            return SuccessResponse()

        except Exception as e:

            logger.error(e)

            return SystemExceptionResponse()


class CaseBaseDeleteAPIView(CaseBaseAPIView):
    """用例模块删除"""

    @APIDOC_DECORATOR.checkParams
    @APIDOC_DECORATOR.start
    @APIDOC_DECORATOR.ApiTag(value = 'case', desc = '测试用例管理')
    @APIDOC_DECORATOR.ApiOperation(method = 'POST', path = '/case/base/delete', summary = '用例删除')
    @APIDOC_DECORATOR.ApiParams(value = 'caseId', type = 'int', require = True, desc = '模块Id')
    @Authentication(isProject = False)
    def post(self, request, *args, **kwargs):
        try:
            body: dict = request.data.copy()

            userId, userName = RequestAuthTokenUtil(
                request = request).get_user_id_and_username()
            projectId = RequestAuthTokenUtil(request = request).get_project()

            # 1. 根据ProjectId判断项目是否存在
            queryset_id = self.Model.objects.filter(
                id = body.get('caseId'), deleted = False, project = projectId)
            if queryset_id.count() == 0:
                return CommonResponse(codeEnums = CommonResultEnums.CASE_BASE_ID_IS_NOT_EXIST)
            # 2. 更新
            with transaction.atomic():
                queryset_id.update(
                    deleted = True,
                    deleteTime = get_time(),
                    updaterId = userId,
                    updaterName = userName,
                    updateTime = get_time(),
                )

            return SuccessResponse()

        except Exception as e:

            logger.error(e)

            return SystemExceptionResponse()


class CaseBaseExportAPIView(CaseBaseAPIView):
    """用例列表导出基于查询条件"""

    @APIDOC_DECORATOR.checkParams
    @APIDOC_DECORATOR.start
    @APIDOC_DECORATOR.ApiTag(value = 'case', desc = '测试用例管理')
    @APIDOC_DECORATOR.ApiOperation(method = 'POST', path = '/case/base/export', summary = '用例列表导出(基于查询条件)')
    @APIDOC_DECORATOR.ApiParams(value = 'runEndTime', type = 'int', desc = '执行结束时间')
    @APIDOC_DECORATOR.ApiParams(value = 'runStartTime', type = 'int', desc = '执行开始时间')
    @APIDOC_DECORATOR.ApiParams(value = 'createEndTime', type = 'int', desc = '创建结束时间')
    @APIDOC_DECORATOR.ApiParams(value = 'createStartTime', type = 'int', desc = '创建开始时间')
    @APIDOC_DECORATOR.ApiParams(value = 'creatorId', type = 'int', desc = '创建人')
    @APIDOC_DECORATOR.ApiParams(value = 'caseRunnerId', type = 'int', desc = '执行人Id')
    @APIDOC_DECORATOR.ApiParams(value = 'caseVindicatorId', type = 'int', desc = '责任人Id')
    @APIDOC_DECORATOR.ApiParams(value = 'caseImportance', type = 'int', desc = '优先级',
                                remark = get_enum_str_list(enumObj = CaseImportanceEnum))
    @APIDOC_DECORATOR.ApiParams(value = 'caseStatus', type = 'int', desc = '用例状态',
                                remark = get_enum_str_list(enumObj = CaseStatusEnum))
    @APIDOC_DECORATOR.ApiParams(value = 'caseTitle', type = 'string', require = False, desc = '用例标题')
    @APIDOC_DECORATOR.ApiParams(value = 'caseModuleId', type = 'int', require = False, desc = '用例模块id')
    @APIDOC_DECORATOR.ApiParams(value = 'pageSize', type = 'int', require = True, desc = '每页数量')
    @APIDOC_DECORATOR.ApiParams(value = 'pageIndex', type = 'int', require = True, desc = '页码')
    @Authentication(isProject = True)
    def post(self, request, *args, **kwargs):
        try:

            return SuccessResponse()
        except Exception as e:

            logger.error(e)

            return SystemExceptionResponse()


class CaseBaseImportAPIView(CaseBaseAPIView):
    """用例列表导入"""

    @APIDOC_DECORATOR.checkParams
    @APIDOC_DECORATOR.start
    @APIDOC_DECORATOR.ApiTag(value = 'case', desc = '测试用例管理')
    @APIDOC_DECORATOR.ApiOperation(method = 'POST', path = '/case/base/import', summary = '用例列表导入')
    @APIDOC_DECORATOR.ApiParams(value = 'importId', require = True, type = 'int', desc = '文件导入id')
    @Authentication(isProject = True)
    def post(self, request, *args, **kwargs):

        try:
            projectId = RequestAuthTokenUtil(request = request).get_project()
            importId = request.data.copy().get('importId')
            userId, userName = RequestAuthTokenUtil(
                request = request).get_user_id_and_username()
            caseImportRecord = CaseImportRecord.objects.filter(id = importId, deleted = False)
            if caseImportRecord.count() == 0:
                return CommonResponse(codeEnums = CommonResultEnums.CASE_IMPORT_ID_IS_NOT_EXIST)

            filePath = caseImportRecord.first().filePath
            data = read_case_import_file(project = projectId, filePath = filePath)
            array = data.get('array')

            # 批量保存测试用例
            caseImportDataList = []
            for i in array:
                caseImportDataList.append(self.Model(
                    caseSteps = i.get('caseSteps'),
                    caseTitle = i.get('caseTitle'),
                    casePreCondition = i.get('casePreCondition'),
                    caseStatus = i.get('caseStatus'),
                    caseImportance = i.get('caseImportance'),
                    caseVindicatorName = i.get('caseVindicatorName'),
                    caseVindicatorId = i.get('caseVindicatorId'),
                    remark = i.get('remark'),
                    caseModuleId = i.get('caseModuleId'),
                    project = projectId,
                    creatorId = userId,
                    creatorName = userName,
                ))

            with transaction.atomic():
                self.Model.objects.bulk_create(caseImportDataList)

            return SuccessResponse(result = data)

        except PioneerBaseExceptions as e:

            logger.error(e)

            return PioneerBaseExceptionResponse(message = f'{e}')

        except Exception as e:

            logger.error(e)

            return SystemExceptionResponse()


class CaseBaseImportCheckAPIView(CaseBaseAPIView):
    """用例列表导入"""

    @APIDOC_DECORATOR.checkParams
    @APIDOC_DECORATOR.start
    @APIDOC_DECORATOR.ApiTag(value = 'case', desc = '测试用例管理')
    @APIDOC_DECORATOR.ApiOperation(method = 'POST', path = '/case/base/importCheck', summary = '用例导入校验')
    @APIDOC_DECORATOR.ApiParams(value = 'importId', require = True, type = 'int', desc = '文件导入id')
    @Authentication(isProject = True)
    def post(self, request, *args, **kwargs):

        try:
            projectId = RequestAuthTokenUtil(request = request).get_project()
            importId = request.data.copy().get('importId')

            caseImportRecord = CaseImportRecord.objects.filter(id = importId, deleted = False)
            if caseImportRecord.count() == 0:
                return CommonResponse(codeEnums = CommonResultEnums.CASE_IMPORT_ID_IS_NOT_EXIST)

            filePath = caseImportRecord.first().filePath

            data = check_case_import_file(project = projectId, filePath = filePath)

            failureCount = data.get('failureCount')
            with transaction.atomic():
                caseImportRecord.update(
                    isCheck = True if failureCount == 0 else False,
                    failureCount = failureCount,
                    total = data.get('total'),
                    successCount = data.get('successCount'),
                    content = data.get('array'),
                )
            return SuccessResponse(result = data)

        except PioneerBaseExceptions as e:

            logger.error(e)

            return PioneerBaseExceptionResponse(message = f'{e}')

        except Exception as e:

            logger.error(e)

            return SystemExceptionResponse()


class CaseBaseImportTemplateAPIView(CaseBaseAPIView):
    """用例列表导入模板下载"""

    @APIDOC_DECORATOR.checkParams
    @APIDOC_DECORATOR.start
    @APIDOC_DECORATOR.ApiTag(value = 'case', desc = '测试用例管理')
    @APIDOC_DECORATOR.ApiOperation(method = 'POST', path = '/case/base/template', summary = '测试用例导入模板下载')
    @Authentication(isProject = False)
    def get(self, request, *args, **kwargs):
        try:
            file_name = parse.quote("测试用例导入模板")

            file = open(f'{BASE_DIR}/media/file/template/caseimport.xlsx', 'rb')
            response = StreamingHttpResponse(file)
            response['Content-Type'] = 'application/ms-excel'
            response['Content-Disposition'] = f'attachment;filename="{file_name}.xlsx"'
            return response

        except Exception as e:

            logger.error(e)

            return SystemExceptionResponse()


class CaseImportFileUpload(CaseBaseAPIView):
    """
    用例导入文件上传
    return: importId 导入文件id
    """

    @APIDOC_DECORATOR.checkParams
    @APIDOC_DECORATOR.start
    @APIDOC_DECORATOR.ApiTag(value = 'case', desc = '测试用例管理')
    @APIDOC_DECORATOR.ApiOperation(method = 'POST', path = '/case/base/upload', summary = '测试用例导入文件上传')
    @APIDOC_DECORATOR.ApiParams(value = 'type', require = True, type = 'int', desc = '导入文件类型',
                                remark = get_enum_str_list(enumObj = CaseImportTypeEnum))
    @APIDOC_DECORATOR.ApiParams(value = 'file', require = True, type = 'file', desc = '文件')
    @Authentication(isProject = False)
    def post(self, request, *args, **kwargs):

        try:
            userId, userName = RequestAuthTokenUtil(
                request = request).get_user_id_and_username()
            files = request.FILES.get('file')
            type = request.data.get('type')
            flag, data = upload_file(file = files)
            if flag:
                with transaction.atomic():
                    caseImportRecord = CaseImportRecord.objects.create(
                        filePath = data.get('url'),
                        fileName = data.get('name'),
                        type = type,
                        creatorId = userId,
                        creatorName = userName
                    )
                data['importId'] = caseImportRecord.id
                return SuccessResponse(result = data)
            else:
                return ParamsErrorResponse(code = 41001, message = data)

        except Exception as e:

            logger.error(e)

            return SystemExceptionResponse()
